package net.lovesrc.allin.jobs.backup;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.biz.gt.GtPreOrder;
import net.lovesrc.allin.biz.gt.GtService;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Profile("live")
public class GtAutoBidJyJob extends BaseJob {

    @Autowired
    private GtService gtService;

    @Override
    public void runOnce() {
        List<JSONObject> newRows = queryForRows(jdbcTemplate, "select * from t_gt_jy where status = 'New'");
        if (newRows == null || newRows.isEmpty()) {
            return;
        }
        String mobile = jdbcTemplate.queryForObject("select mobile from v_gt_other_account order by updateTime desc limit 1", String.class);
        List<GtPreOrder> preBuyOrders = gtService.getPreBuyOrders(mobile);
        for (JSONObject newRow : newRows) {
            Integer newJyId = newRow.getInteger("jyId");
            Date insertTime = newRow.getDate("insertTime");
            String sellerMobile = newRow.getString("sellerMobile");

            // 2分钟或者在买入列表中
            if (System.currentTimeMillis() - insertTime.getTime() >= RandomUtils.nextInt(90, 100) * DateUtils.MILLIS_PER_SECOND) {
                gtService.buyJy(sellerMobile, newJyId);
                continue;
            }
            for (GtPreOrder preBuyOrder : preBuyOrders) {
                if (preBuyOrder.getId().equals(newJyId)) {
                    gtService.buyJy(sellerMobile, newJyId);
                    break;
                }
            }
        }
    }

    @Override
    protected long intervalMilliseconds() {
        return TimeUnit.SECONDS.toMillis(1);
    }

}
